package com.simplehire.service;

import com.simplehire.model.User;
import com.simplehire.model.UserRole;
import com.simplehire.repository.UserRepository;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {
    
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    
    public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }
    
    public User save(User user) {
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userRepository.save(user);
    }
    
    public User updateUser(User user) {
        return userRepository.save(user);
    }
    
    public boolean userExists(String username) {
        return userRepository.existsByUsername(username);
    }
    
    public boolean emailExists(String email) {
        return userRepository.existsByEmail(email);
    }
    
    public User findByUsername(String username) {
        return userRepository.findByUsername(username).orElse(null);
    }
    
    public User findById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
    
    public List<User> findAllUsers() {
        return userRepository.findAll();
    }
    
    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
    
    public void resetPassword(Long id, String newPassword) {
        User user = findById(id);
        if (user != null) {
            user.setPassword(passwordEncoder.encode(newPassword));
            userRepository.save(user);
        }
    }
    
    // 检查用户是否有特定角色
    public boolean hasRole(User user, UserRole role) {
        return user != null && user.getRoles() != null && user.getRoles().contains(role);
    }
    
    // 获取所有管理员用户
    public List<User> findAllAdmins() {
        return userRepository.findAll().stream()
                .filter(user -> user.getRoles().contains(UserRole.ADMIN))
                .collect(java.util.stream.Collectors.toList());
    }
}